<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-page-header @back="handleBack" content="新增商品SKU" />
        </div>
      </template>
      
      <el-form
        ref="skuRef"
        :model="form"
        :rules="rules"
        label-width="200px"
        class="sku-form"
        size="default">
        
        <!-- SPU选择 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="SPU" prop="spuId">
              <el-select
                v-model="form.spuId"
                placeholder="请选择或输入SPU名称搜索"
                clearable
                filterable
                :filter-method="handleSpuSearch"
                @visible-change="handleSpuVisibleChange"
                class="full-width">
                <el-option
                  v-for="spu in productSpuList"
                  :key="spu.id"
                  :label="spu.name"
                  :value="spu.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- SKU名称 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU标题" prop="skuName">
              <el-input v-model="form.skuName" placeholder="请输入SKU标题" class="full-width" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- SKU编码 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="SKU编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入SKU编码" class="full-width" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 销售价 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="销售价" prop="price">
              <el-input v-model="form.price" placeholder="请输入销售价">
                <template #prepend>￥</template>
              </el-input>
            </el-form-item>
          </el-col>
          
          <!-- 原价 -->
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input v-model="form.originalPrice" placeholder="请输入原价">
                <template #prepend>￥</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 成本价 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="成本价" prop="costPrice">
              <el-input v-model="form.costPrice" placeholder="请输入成本价">
                <template #prepend>￥</template>
              </el-input>
            </el-form-item>
          </el-col>
          
          <!-- 库存数量 -->
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stock">
              <el-input v-model="form.stock" placeholder="请输入库存数量">
                <template #append>件</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 库存预警值 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存预警值" prop="lowStock">
              <el-input v-model="form.lowStock" placeholder="请输入库存预警值">
                <template #append>件</template>
              </el-input>
            </el-form-item>
          </el-col>
          
          <!-- 重量 -->
          <el-col :span="12">
            <el-form-item label="重量" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入重量">
                <template #append>g</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 体积 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="体积" prop="volume">
              <el-input v-model="form.volume" placeholder="请输入体积">
                <template #append>cm³</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品图片 -->
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品图片" prop="productImages">
              <image-upload
                v-model="form.productImages"
                :limit="20"
                multiple
                @change="handleImageChange" />
              <div class="form-tip">
                支持上传多张图片，最多5张，按上传顺序排序
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 规格可选项（循环渲染分组）：修复prop路径 -->
        <div v-for="(group, groupIdx) in data.specGroups" :key="groupIdx" class="spec-group">
          <el-divider
            content-position="left"
            v-if="getSpecTypeData(group.type)?.specItemGroup.length">
            {{ group.label }}
          </el-divider>

          <el-row :gutter="20">
            <!-- 分组内的表单项：prop路径改为"form.specSelections"的子路径 -->
            <el-col 
              v-for="(item, itemIdx) in getSpecTypeData(group.type)?.specItemGroup"
              :key="`spec-${group.type}-${itemIdx}`"
              :span="12">
              <el-form-item
                :label="item.specName"
                :prop="`specSelections.${group.type}.${itemIdx}`"
                :rules="[{
                  required: true,
                  message: `${item.specName}不能为空`,
                  trigger: 'change',
                }]">
                <!-- 修复：v-model绑定form内的specSelections -->
                <el-select
                  v-model="form.specSelections[group.type][itemIdx]"
                  placeholder="请选择"
                  clearable
                  class="full-width">
                  <el-option
                    v-for="(option, optIdx) in item.specValueGroup"
                    :key="`opt-${group.type}-${itemIdx}-${optIdx}`"
                    :label="option"
                    :value="option" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 操作按钮 -->
        <el-row class="form-actions">
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="submitForm" size="default">保存</el-button>
              <el-button @click="handleBack" size="default">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="SkuAdd">
// 接口引入
import { addSku } from "@/api/product/sku";
import { listProductCategory } from "@/api/product/productCategory";
import { listProductSpu } from "@/api/product/productSpu";
import {
  getProductSpecTemplate,
  listProductSpecTemplate,
  getProductSpecTemplateGrouped,
} from "@/api/product/productSpecTemplate";

// 依赖引入
import { useRouter, useRoute } from "vue-router";
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from "vue";
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

// 下拉选择数据源（非响应式，用ref声明）
const productCategoryOptions = ref([]);
const productSpuList = ref([]);
const productSpecTemplateList = ref([]);
const selectedTemplateSpecs = ref([]); // 选中模板的属性列表

// 查询参数（非响应式，用ref声明）
const querySpuParams = ref({ pageSize: 9999, name: "" });
const queryAllParams = ref({ pageSize: 9999 });

// 核心响应式数据（统一用reactive管理，避免分散定义）
const data = reactive({
  // 表单基础数据
  form: {
    spuId: null,
    skuName: null,
    code: null,
    // categoryId: null,
    templateId: null,
    specValues: [],
    price: null,
    originalPrice: null,
    costPrice: null,
    stock: null,
    lowStock: null,
    weight: null,
    volume: null,
    productImages: [],
    status: 1,
    // 规格选中值（按specType分组，数组下标对应属性下标）
    specSelections: {
      0: [], // specType=0（售卖属性）选中值
      1: [], // specType=1（基础属性）选中值
      3: [], // specType=3（overview属性）选中值
      4: [], // specType=4（其它属性）选中值
    },
  },
  // 表单校验规则
  rules: {
    spuId: [{ required: true, message: "所属SPU不能为空", trigger: "blur" }],
    code: [{ required: true, message: "SKU编码不能为空", trigger: "blur" }],
    price: [{ required: true, message: "销售价不能为空", trigger: "blur" }],
    stock: [{ required: true, message: "库存数量不能为空", trigger: "blur" }],
    productImages: [
      {
        required: false,
        // validator: (rule, value, callback) => {
        //   if (!value || value.length === 0) {
        //     callback(new Error("请至少上传一张商品图片"));
        //   } else {
        //     callback();
        //   }
        // },
        trigger: "change",
      },
    ],
  },
  // 规格分组配置（type对应specType，label对应分组名称）
  specGroups: [
    { type: 0, label: "售卖属性" },
    { type: 1, label: "基础属性" },
    { type: 2, label: "overview属性" },
    { type: 3, label: "尺寸属性" },
  ],
  // 规格数据源（用户提供的specTypes）
  specData: {},
  specNameGroup: [],
  specValueGroup: [],
});

// 解构响应式数据（方便访问，非必需但提升可读性）
const { form, rules } = toRefs(data);

/**
 * 根据specType获取对应的规格数据
 * @param {number} type - specType（0/1/3/4）
 * @returns {object|null} 对应type的规格组数据
 */
const getSpecTypeData = (type) => {
  return (
    data.specData.specTypes?.find((item) => item.specType === type) || null
  );
};

/** 返回列表页面 */
const handleBack = () => {
  const obj = { path: "/product/sku" };
  proxy.$tab.closeOpenPage(obj);
};

/** 提交表单：无需单独添加specSelections（已在form内） */
const submitForm = () => {
  proxy.$refs["skuRef"].validate((valid) => {
    // console.log(form.value, "这是表单值");
    if (valid) {
      // if (1) {
      // 关键修改：submitForm直接使用form.value，无需额外拼接specSelections
      const submitForm = {
        ...form.value,
        specValues: form.value.specValues.filter((item) =>
          item.specValue?.trim()
        ),
        specValueGroupList: (() => {
          const specValueGroup = [];
          // specSelections是对象（结构：{0: [], 1: [], 3: [], 4: []}）
          // 先通过Object.values获取其值数组（每个值是一个子数组）
          const specArrays = Object.values(form.value.specSelections);
          // 遍历每个子数组，收集所有元素
          specArrays.forEach((arr) => {
            specValueGroup.push(...arr);
          });
          return specValueGroup;
        })(),
        specNameGroupList: getSpecNameGroup(data.specData),
        // 移除：specSelections: data.specSelections（已在form内）
      };
      console.log(submitForm, "这是提交值");
      addSku(submitForm)
        .then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          handleBack();
        })
        .catch((err) => {
          proxy.$modal.msgError(err.msg || "新增失败，请重试");
        });
    }
  });
};

/** 处理图片上传：设置排序与关联SPU */
const handleImageChange = (images) => {
  form.value.productImages = images.map((img, index) => ({
    url: img.url,
    sort: index + 1,
    spuId: form.value.spuId || null,
  }));
};

/** 获取商品分类树形结构 */
const getCategoryTreeselect = () => {
  listProductCategory(queryAllParams.value).then((response) => {
    productCategoryOptions.value = [];
    const rootNode = { id: 0, name: "顶级节点", children: [] };
    rootNode.children = proxy.handleTree(response.data, "id", "parentId");
    productCategoryOptions.value.push(rootNode);
  });
};

/** 获取SPU列表 */
const getSpuList = () => {
  // 修复：使用解构和重新构建参数对象的方式，避免传递Vue内部属性
  const cleanParams = {
    pageSize: querySpuParams.value.pageSize,
    name: querySpuParams.value.name
  };
  listProductSpu(cleanParams).then((response) => {
    productSpuList.value = response.rows;
  });
};

/** 获取规格可选值（接口调用，保留原逻辑） */
const getProductSpecTemplateGroupedApi = (spuId) => {
  getProductSpecTemplateGrouped(spuId).then((res) => {
    console.log(JSON.stringify(res.data), "这是可选值");
    data.specData = res.data;
    // 初始化规格选中值：默认选中每个属性的第一项
    data.specGroups.forEach((group) => {
      const specTypeData = getSpecTypeData(group.type);
      if (specTypeData?.specItemGroup) {
        // 从data.specSelections改为form.specSelections
        form.value.specSelections[group.type] = specTypeData.specItemGroup.map(
          (item) => {
            return item.specValueGroup[0] || ""; // 取第一项作为默认值
          }
        );
      }
    });
  });
};

/** 获取属性模板列表 */
const getTemplateList = () => {
  listProductSpecTemplate(queryAllParams.value).then((response) => {
    // 处理status为字符串（适配下拉选择）
    productSpecTemplateList.value = response.rows.map((row) => ({
      ...row,
      status: String(row.status),
    }));
  });
};
/**
 * 按顺序提取specData中所有specName，组成specNameGroup数组
 * 顺序规则：先按specTypes数组顺序，再按每个specType内specItemGroup的顺序
 * @returns {string[]} 按顺序排列的specName数组
 */
const getSpecNameGroup = (specData) => {
  // 1. 初始化结果数组，避免空引用
  const specNameGroup = [];

  // 2. 安全获取specTypes数组（防止data或specData为空导致报错）
  const specTypes = specData?.specTypes || [];

  // 3. 第一层遍历：按specTypes原顺序遍历（如specType=0、1、2、3的顺序）
  specTypes.forEach((specTypeItem) => {
    // 4. 安全获取当前specType的specItemGroup数组
    const specItemGroup = specTypeItem?.specItemGroup || [];

    // 5. 第二层遍历：按specItemGroup原顺序遍历（如Color、Lighted、Material的顺序）
    specItemGroup.forEach((item) => {
      // 6. 过滤无效值（避免添加undefined、空字符串等）
      if (item?.specName && item.specName.trim() !== "") {
        specNameGroup.push(item.specName);
      }
    });
  });

  return specNameGroup;
};
/** SPU搜索防抖处理 */
const debounce = (fn, delay = 300) => {
  let timer = null;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

// 使用防抖处理SPU搜索
const handleSpuSearch = debounce((inputValue) => {
  // 创建纯净的查询参数对象，避免传递Vue内部属性
  const searchParams = {
    pageSize: 9999,
    name: inputValue || ""
  };
  listProductSpu(searchParams).then((response) => {
    productSpuList.value = response.rows;
  });
});

// 处理下拉框显示/隐藏事件
const handleSpuVisibleChange = (visible) => {
  if (visible) {
    // 显示下拉框时，重新加载完整的SPU列表
    const searchParams = {
      pageSize: 9999
    };
    listProductSpu(searchParams).then((response) => {
      productSpuList.value = response.rows;
    });
  }
};

/** 模板切换：加载属性并初始化specValues（保留原逻辑，按需启用） */
const handleTemplateChange = (templateId) => {
  selectedTemplateSpecs.value = [];
  form.value.specValues = [];

  if (templateId) {
    getProductSpecTemplate(templateId).then((response) => {
      const template = response.data;
      // 过滤有效属性（关联关系+属性本身存在）
      const validSpecs = (template.relationList || [])
        .filter((relation) => relation.productSpec && relation.productSpec.id)
        .map((relation) => ({
          ...relation.productSpec,
          relation: relation, // 保留关联信息（排序、是否必填）
        }));

      // 按排序字段排序
      validSpecs.sort(
        (a, b) => (a.relation.sort || 0) - (b.relation.sort || 0)
      );
      selectedTemplateSpecs.value = validSpecs;

      // 初始化specValues：与属性一一对应
      form.value.specValues = validSpecs.map((spec) => ({
        specId: spec.id,
        specValue: "",
      }));
    });
  }
};

/** 页面初始化加载数据 */
onMounted(() => {
  getCategoryTreeselect();
  getSpuList();
  getTemplateList();
  getProductSpecTemplateGroupedApi(10);
});
</script>

<style scoped>
.sku-form {
  padding: 20px;
}

.full-width {
  width: 100%;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.spec-group {
  margin-bottom: 20px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
